<template>
    <div class="register grid-content bg-purple">
        <el-form
            title="注册新用户"
            ref="registerForm"
            :model="registerForm"
            status-icon
            :rules="rules"
            label-width="100px"
            class="demo-registerForm"
        >
            <el-form-item label="用户名" prop="username">
                <el-input v-model="registerForm.username" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="registerForm.mobile" />
            </el-form-item>
            <el-form-item label="验证码" prop="validateCode">
                <input v-model="validateCode" placeholder="请输入验证码" />&nbsp;
                <button type="button" @click="sendCode($event)">{{ sendCodeButton }}</button>
            </el-form-item>
            <el-form-item label="密码" prop="pwd">
                <el-input v-model="registerForm.pwd" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
                <el-input v-model="registerForm.checkPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('registerForm')">注册</el-button>
                <el-button @click="resetForm('registerForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import request from "@/utils/request";

export default {
    name: "Register",
    data() {
        var checkUserName = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("用户名不能为空"));
            }
            var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
            if (!uPattern.test(value)) {
                callback(
                    new Error("请输入4到16位（字母，数字，下划线，减号）")
                );
            } else {
                callback();
            }
        };
        var checkMobile = (rule, value, callback) => {
            const mobilePattern = /^1\d{10}$/;
            if (!mobilePattern.test(value)) {
                callback(new Error("请输入正确的手机号"));
            } else {
                callback();
            }
        };
        var validatePass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入密码"));
            } else {
                if (this.registerForm.checkPass !== "") {
                    this.$refs.registerForm.validateField("checkPass");
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.registerForm.pwd) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
        return {
            registerForm: {
                pwd: "",
                checkPass: "",
                username: "",
                mobile: "",
            },
            validateCode: "",
            rules: {
                pwd: [{ validator: validatePass, trigger: "blur" }],
                checkPass: [{ validator: validatePass2, trigger: "blur" }],
                username: [{ validator: checkUserName, trigger: "blur" }],
                mobile: [{ validator: checkMobile, trigger: "blur" }],
            },
            sendCodeButton: "发送验证码",
            mobileCode: "",
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (
                    this.mobileCode !== this.validateCode ||
                    this.validateCode == ""
                ) {
                    this.$message.error("验证码错误!");
                    return;
                }

                if (valid) {
                    request({
                        url: "/rest/user/register",
                        method: "post",
                        data: {
                            user: this.registerForm.username,
                            pwd: this.registerForm.pwd,
                            mobile: this.registerForm.mobile,
                        },
                    })
                    .then((res) => {
                        if (res.status) {
                            this.$message({
                                message: "注册成功!",
                                type: "success",
                                center: true,
                            });
                            this.$router.push({ path: "/" });
                        } else {
                            this.$message.error(res.message);
                        }
                    })
                    .catch((e) => {
                        console.error(e);
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        sendCode($event) {
            // 发送验证码
            this.currentTarget = $event.currentTarget;

            request({
                url: "/rest/user/code",
                data: { mobile: this.registerForm.mobile },
                method: "post",
            })
            .then((res) => {
                //console.log(res);
                if (res.status) {
                    this.mobileCode = res.data;
                    this.currentTarget.setAttribute("disabled", true);
                    this.currentTarget.className += "is-disabled";

                    // 计时器
                    let second = 60;
                    const timer = setInterval(() => {
                        second -= 1;
                        if (second > 0) {
                            this.sendCodeButton = second + "秒后获取验证码";
                        } else {
                            this.sendCodeButton = "发送验证码";
                            this.currentTarget.removeAttribute("disabled");
                            this.currentTarget.className.replace("is-disabled", "");
                            clearInterval(timer);
                        }
                    }, 1000);
                } else {
                    this.$message.error(res.message);
                }
            })
            .catch((e) => {
                console.error(e);
            });
        },
    },
};
</script>
<style scoped>
.register {
    margin: 0px auto;
    width: 30%;
}
.register form {
    margin-top: 25vh;
}
.el-form-item__content {
    display: flex;
}
</style>
